<!doctype html>



  


<html class="theme-next pisces use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />




  
  
  
  

  
    
    
  

  

  

  

  

  
    
    
    <link href="//fonts.googleapis.com/css?family=Lato:300,300italic,400,400italic,700,700italic&subset=latin,latin-ext" rel="stylesheet" type="text/css">
  






<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.1" rel="stylesheet" type="text/css" />


  <meta name="keywords" content="Editor," />








  <link rel="shortcut icon" type="image/x-icon" href="/favicon.ico?v=5.1.1" />






<meta name="description" content="倒序匹配获取正确区域名称问题：有些区域直属于省，但其区域编码按层级又在市级别以下，如何正确获取这些区域的名称方案：递归查找时，标识是否找到，若找到才倒序插入列表123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051&amp;lt;html&amp;gt;&amp;lt;head&amp;gt;">
<meta name="keywords" content="Editor">
<meta property="og:type" content="article">
<meta property="og:title" content="代码片段">
<meta property="og:url" content="https://gitee.com/icmyfuture/icmyfuture/2017/06/20/code-snippet/index.html">
<meta property="og:site_name" content="icmyfuture">
<meta property="og:description" content="倒序匹配获取正确区域名称问题：有些区域直属于省，但其区域编码按层级又在市级别以下，如何正确获取这些区域的名称方案：递归查找时，标识是否找到，若找到才倒序插入列表123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051&amp;lt;html&amp;gt;&amp;lt;head&amp;gt;">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2021-10-21T14:58:43.282Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="代码片段">
<meta name="twitter:description" content="倒序匹配获取正确区域名称问题：有些区域直属于省，但其区域编码按层级又在市级别以下，如何正确获取这些区域的名称方案：递归查找时，标识是否找到，若找到才倒序插入列表123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051&amp;lt;html&amp;gt;&amp;lt;head&amp;gt;">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    sidebar: {"position":"left","display":"post","offset":12,"offset_float":0,"b2t":false,"scrollpercent":false},
    fancybox: true,
    motion: true,
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://gitee.com/icmyfuture/icmyfuture/2017/06/20/code-snippet/"/>





  <title>代码片段 | icmyfuture</title>
  














</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail ">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">icmyfuture</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">Nothing is true, everthing is permitted</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup">
 <span class="search-icon fa fa-search"></span>
 <input type="text" id="local-search-input" placeholder="search my blog...">
 <div id="local-search-result"></div>
 <span class="popup-btn-close">close</span>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal " itemscope itemtype="http://schema.org/Article">
    <link itemprop="mainEntityOfPage" href="https://gitee.com/icmyfuture/icmyfuture/2017/06/20/code-snippet/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="iDu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/uploads/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="icmyfuture">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">代码片段</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2017-06-20T10:03:26+08:00">
                2017-06-20
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/Technology/" itemprop="url" rel="index">
                    <span itemprop="name">Technology</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="倒序匹配获取正确区域名称"><a href="#倒序匹配获取正确区域名称" class="headerlink" title="倒序匹配获取正确区域名称"></a>倒序匹配获取正确区域名称</h1><p>问题：有些区域直属于省，但其区域编码按层级又在市级别以下，如何正确获取这些区域的名称<br>方案：递归查找时，标识是否找到，若找到才倒序插入列表<br><figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/javascript"</span>&gt;</span><span class="undefined"></span></span><br><span class="line"><span class="undefined">        var list = [];</span></span><br><span class="line"><span class="undefined">        var data = [&#123;</span></span><br><span class="line"><span class="undefined">                value: "51",</span></span><br><span class="line"><span class="undefined">                children: [&#123;</span></span><br><span class="line"><span class="undefined">                    value: "5101",</span></span><br><span class="line"><span class="undefined">                    children: [&#123;</span></span><br><span class="line"><span class="undefined">                        value: "510104",</span></span><br><span class="line"><span class="undefined">                        children: []</span></span><br><span class="line"><span class="undefined">                    &#125;]</span></span><br><span class="line"><span class="undefined">                &#125;]</span></span><br><span class="line"><span class="undefined">            &#125;, &#123;</span></span><br><span class="line"><span class="undefined">                value: "61",</span></span><br><span class="line"><span class="undefined">                children: [&#123;</span></span><br><span class="line"><span class="undefined">                    value: "6101",</span></span><br><span class="line"><span class="undefined">                    children: [&#123;</span></span><br><span class="line"><span class="undefined">                        value: "610101",</span></span><br><span class="line"><span class="undefined">                        children: []</span></span><br><span class="line"><span class="undefined">                    &#125;]</span></span><br><span class="line"><span class="undefined">                &#125;, &#123;</span></span><br><span class="line"><span class="undefined">                    value: "610194",</span></span><br><span class="line"><span class="undefined">                    children: [&#123;</span></span><br><span class="line"><span class="undefined">                        value: "61019401",</span></span><br><span class="line"><span class="undefined">                        children: []</span></span><br><span class="line"><span class="undefined">                    &#125;]</span></span><br><span class="line"><span class="undefined">                &#125;]</span></span><br><span class="line"><span class="undefined">            &#125;];</span></span><br><span class="line"><span class="undefined">        var selectedValue = "61019401";</span></span><br><span class="line"><span class="undefined">        var got = false;</span></span><br><span class="line"><span class="undefined">        var find = function (item) &#123;</span></span><br><span class="line"><span class="undefined">            if (selectedValue.startsWith(item.value)) &#123;</span></span><br><span class="line"><span class="undefined">                if(item.children &amp;&amp; item.children.length &gt; 0) &#123;</span></span><br><span class="line"><span class="undefined">                    for (var j = 0; j &lt; item.children.length; j++) &#123;</span></span><br><span class="line"><span class="undefined">                        find(item.children[j])</span></span><br><span class="line"><span class="undefined">                    &#125;</span></span><br><span class="line"><span class="undefined">                &#125;</span></span><br><span class="line"><span class="undefined">                if (selectedValue == item.value) got = true</span></span><br><span class="line"><span class="undefined">                if (got) &#123;</span></span><br><span class="line"><span class="undefined">                    list.push(item);</span></span><br><span class="line"><span class="undefined">                &#125;</span></span><br><span class="line"><span class="undefined">            &#125;</span></span><br><span class="line"><span class="undefined">        &#125;</span></span><br><span class="line"><span class="undefined">        find(data);</span></span><br><span class="line"><span class="undefined">        console.log(list);</span></span><br><span class="line"><span class="undefined">    </span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure></p>
<h1 id="由列表构建层级"><a href="#由列表构建层级" class="headerlink" title="由列表构建层级"></a>由列表构建层级</h1><h2 id="区域"><a href="#区域" class="headerlink" title="区域"></a>区域</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">private static List&lt;dynamic&gt; GetAreaList(List&lt;QR_Area&gt; areaList, int type, string code = &quot;86&quot;)</span><br><span class="line">&#123;</span><br><span class="line">    var list = new List&lt;dynamic&gt;();</span><br><span class="line">    var l = areaList.Where(a =&gt; (int)a.RealAreaType == type &amp;&amp; (a.SortCode.StartsWith(code) || code == &quot;86&quot;) &amp;&amp; !string.IsNullOrWhiteSpace(a.Name)).</span><br><span class="line">            Select(a =&gt; new &#123;</span><br><span class="line">                value = a.SortCode,</span><br><span class="line">                label = a.Name,</span><br><span class="line">                children = GetAreaList(areaList, type + 1, a.SortCode)</span><br><span class="line">            &#125;).ToList();</span><br><span class="line"></span><br><span class="line">    if (l.Count &gt; 0)</span><br><span class="line">    &#123;</span><br><span class="line">        if (code == &quot;6101&quot;)</span><br><span class="line">        &#123;</span><br><span class="line">            l = l.Where(a =&gt; !a.value.StartsWith(&quot;610194&quot;)).ToList();</span><br><span class="line">        &#125;</span><br><span class="line">        list.AddRange(l);</span><br><span class="line">    &#125;</span><br><span class="line">    else</span><br><span class="line">    &#123;</span><br><span class="line">        list = null;</span><br><span class="line">    &#125;</span><br><span class="line">    return list;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="组织"><a href="#组织" class="headerlink" title="组织"></a>组织</h2><p>构建组织<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">private static dynamic ConstructContractor(List&lt;SimpleContractor&gt; list)</span><br><span class="line">&#123;</span><br><span class="line">    if (list == null || list.Count == 0) return null;</span><br><span class="line">    var l = list;</span><br><span class="line">    var top = l[0];</span><br><span class="line">    if (l.Count &gt; 1)</span><br><span class="line">    &#123;</span><br><span class="line">        l.RemoveAt(0);</span><br><span class="line">        var groups = l.GroupBy(c =&gt; c.C.Substring(0, top.C.Length + 4));</span><br><span class="line">        return new &#123; Code = top.C, Name = top.N, Children = groups.Select(g =&gt; &#123;</span><br><span class="line">            var sub = g.ToList().OrderBy(c =&gt; c.C.Length).OrderBy(c =&gt; c.C).ToList();</span><br><span class="line">            if (sub[0].C.Length &gt; top.C.Length + 4) return null;</span><br><span class="line">            return ConstructContractor(sub);</span><br><span class="line">        &#125;).Where(x =&gt; x != null).ToList() &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">    return new &#123; Code = top.C, Name = top.N &#125;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>获取组织<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">private static dynamic GetContractor(dynamic contractor, string code)</span><br><span class="line">&#123;</span><br><span class="line">    if (contractor.Code.Equals(code)) return contractor;</span><br><span class="line"></span><br><span class="line">    if (code.StartsWith(contractor.Code))</span><br><span class="line">    &#123;</span><br><span class="line">        if (contractor.Children != null &amp;&amp; contractor.Children.Count &gt; 0)</span><br><span class="line">        &#123;</span><br><span class="line">            for (var i = 0; i &lt; contractor.Children.Count; i++)</span><br><span class="line">            &#123;</span><br><span class="line">                var result = GetContractor(contractor.Children[i], code);</span><br><span class="line">                if (result != null) return result;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    return null;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h2 id="找出字符串的最大深度"><a href="#找出字符串的最大深度" class="headerlink" title="找出字符串的最大深度"></a>找出字符串的最大深度</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">findDepth</span><span class="params">(s <span class="keyword">string</span>)</span> <span class="title">int</span></span> &#123;</span><br><span class="line">    <span class="keyword">var</span> current <span class="keyword">int</span> = <span class="number">0</span></span><br><span class="line">    <span class="keyword">var</span> max <span class="keyword">int</span> = <span class="number">0</span></span><br><span class="line"></span><br><span class="line">    b := []<span class="keyword">byte</span>(s)</span><br><span class="line">    <span class="keyword">for</span> i := <span class="number">0</span>; i &lt; <span class="built_in">len</span>(b); i++ &#123;</span><br><span class="line">        x := b[i]</span><br><span class="line">        <span class="keyword">if</span> x == <span class="string">'('</span> &#123;</span><br><span class="line">            current += <span class="number">1</span></span><br><span class="line">            <span class="keyword">if</span> current &gt; max &#123;</span><br><span class="line">                max = current</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> x == <span class="string">')'</span> &amp;&amp; current &gt; <span class="number">0</span> &#123;</span><br><span class="line">            current -= <span class="number">1</span></span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> max - current</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight md"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">input:  (1+2+(1*2)(1+2))</span><br><span class="line">output: 3</span><br></pre></td></tr></table></figure>
<h2 id="找出序列中第K大的数"><a href="#找出序列中第K大的数" class="headerlink" title="找出序列中第K大的数"></a>找出序列中第K大的数</h2><figure class="highlight go"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">getKMax</span><span class="params">(s []<span class="keyword">int</span>, k <span class="keyword">int</span>)</span> <span class="title">int</span></span> &#123;</span><br><span class="line">    <span class="keyword">if</span> k &lt; <span class="number">1</span> || <span class="built_in">len</span>(s) &lt; k &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="number">-1</span></span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将前k个数构建最小堆</span></span><br><span class="line">    constructMinHeap(s, k)</span><br><span class="line"></span><br><span class="line">    <span class="comment">//将k以后的数与s[0]进行比较</span></span><br><span class="line">    <span class="comment">//若比s[0]大, 则与s[0]交换, 并自顶向下重构最小堆</span></span><br><span class="line">    <span class="keyword">for</span> i := k; i &lt; <span class="built_in">len</span>(s); i++ &#123;</span><br><span class="line">        <span class="keyword">if</span> s[i] &lt;= s[<span class="number">0</span>] &#123;</span><br><span class="line">            <span class="keyword">continue</span></span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        s[<span class="number">0</span>], s[i] = s[i], s[<span class="number">0</span>]</span><br><span class="line"></span><br><span class="line">        x := <span class="number">0</span></span><br><span class="line">        <span class="keyword">for</span> x &lt; k &#123;</span><br><span class="line">            x = reConstructMinHeap(s, k, x)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> s[<span class="number">0</span>]</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">reConstructMinHeap</span><span class="params">(s []<span class="keyword">int</span>, k <span class="keyword">int</span>, current <span class="keyword">int</span>)</span> <span class="title">int</span></span> &#123;</span><br><span class="line">    <span class="comment">//将current与 left=2*current+1 right=2*current+2 中最小的进行比较, 若current较大，则进行交换</span></span><br><span class="line">    left := <span class="number">2</span>*current + <span class="number">1</span></span><br><span class="line">    <span class="keyword">if</span> left &lt; k &#123;</span><br><span class="line">        minIndex := left</span><br><span class="line">        right := <span class="number">2</span>*current + <span class="number">2</span></span><br><span class="line">        <span class="keyword">if</span> right &lt; k &amp;&amp; s[right] &lt; s[left] &#123;</span><br><span class="line">            minIndex = right</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> s[minIndex] &lt; s[current] &#123;</span><br><span class="line">            s[current], s[minIndex] = s[minIndex], s[current]</span><br><span class="line">            <span class="keyword">return</span> minIndex</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">return</span> k</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">func</span> <span class="title">constructMinHeap</span><span class="params">(s []<span class="keyword">int</span>, k <span class="keyword">int</span>)</span></span> &#123;</span><br><span class="line">    <span class="keyword">for</span> i := k - <span class="number">1</span>; i &gt; <span class="number">0</span>; i = i - <span class="number">2</span> &#123;</span><br><span class="line">        parent := (i - <span class="number">1</span>) / <span class="number">2</span></span><br><span class="line">        left := <span class="number">2</span>*parent + <span class="number">1</span></span><br><span class="line">        right := <span class="number">2</span>*parent + <span class="number">2</span></span><br><span class="line">        minIndex := left</span><br><span class="line">        <span class="keyword">if</span> right &lt; k &amp;&amp; s[right] &lt; s[left] &#123;</span><br><span class="line">            minIndex = right</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> s[parent] &gt; s[minIndex] &#123;</span><br><span class="line">            s[parent], s[minIndex] = s[minIndex], s[parent]</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<figure class="highlight md"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">input:  [10,9,8,7,6,5,4,3,2,1], 3</span><br><span class="line">output: 8</span><br></pre></td></tr></table></figure>
      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <div>
      
        

      
    </div>

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Editor/" rel="tag"># Editor</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2017/06/20/jetbrains-note/" rel="next" title="JetBrains IDE 杂记">
                <i class="fa fa-chevron-left"></i> JetBrains IDE 杂记
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/01/29/iarc-000/" rel="prev" title="架构之旅">
                架构之旅 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          
  <div class="comments" id="comments">
    
  </div>


        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap" >
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
          <img class="site-author-image" itemprop="image"
               src="/uploads/avatar.jpg"
               alt="iDu" />
          <p class="site-author-name" itemprop="name">iDu</p>
           
              <p class="site-description motion-element" itemprop="description">诗酒风流品花月</p>
          
        </div>
        <nav class="site-state motion-element">

          
            <div class="site-state-item site-state-posts">
              <a href="/archives">
                <span class="site-state-item-count">23</span>
                <span class="site-state-item-name">日志</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-categories">
              <a href="/categories/index.html">
                <span class="site-state-item-count">3</span>
                <span class="site-state-item-name">分类</span>
              </a>
            </div>
          

          
            
            
            <div class="site-state-item site-state-tags">
              <a href="/tags/index.html">
                <span class="site-state-item-count">7</span>
                <span class="site-state-item-name">标签</span>
              </a>
            </div>
          

        </nav>

        

        <div class="links-of-author motion-element">
          
            
              <span class="links-of-author-item">
                <a href="https://github.com/icmyfuture" target="_blank" title="GitHub">
                  
                    <i class="fa fa-fw fa-github"></i>
                  
                  GitHub
                </a>
              </span>
            
              <span class="links-of-author-item">
                <a href="https://weibo.com/u/1865769731" target="_blank" title="Weibo">
                  
                    <i class="fa fa-fw fa-weibo"></i>
                  
                  Weibo
                </a>
              </span>
            
          
        </div>

        
        

        
        

        


      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#倒序匹配获取正确区域名称"><span class="nav-number">1.</span> <span class="nav-text">倒序匹配获取正确区域名称</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#由列表构建层级"><span class="nav-number">2.</span> <span class="nav-text">由列表构建层级</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#区域"><span class="nav-number">2.1.</span> <span class="nav-text">区域</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#组织"><span class="nav-number">2.2.</span> <span class="nav-text">组织</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#找出字符串的最大深度"><span class="nav-number">2.3.</span> <span class="nav-text">找出字符串的最大深度</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#找出序列中第K大的数"><span class="nav-number">2.4.</span> <span class="nav-text">找出序列中第K大的数</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright" >
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">iDu</span>
</div>


<div class="powered-by">
  由 <a class="theme-link" href="https://hexo.io">Hexo</a> 强力驱动
</div>

<div class="theme-info">
  主题 -
  <a class="theme-link" href="https://github.com/iissnan/hexo-theme-next">
    NexT.Pisces
  </a>
</div>


        

        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>

  
  <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>

  
  <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>

  
  <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.1"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.1"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.1"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.1"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.1"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.1"></script>



  


  




	





  





  





  






  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'manual') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  

  

  

</body>
</html>
